package com.yowasa.xiuxian.engine.message.item;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yowasa.xiuxian.annoations.CMD;
import com.yowasa.xiuxian.engine.CommonEngine;
import com.yowasa.xiuxian.engine.ItemEngine;
import com.yowasa.xiuxian.engine.item.ItemInterface;
import com.yowasa.xiuxian.engine.message.CmdMessageHandler;
import com.yowasa.xiuxian.entity.bo.item.UserItemBo;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.enums.CmdScopeEnum;
import com.yowasa.xiuxian.entity.enums.QualityEnum;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuXianDrawing;
import com.yowasa.xiuxian.entity.po.XiuXianExtend;
import com.yowasa.xiuxian.entity.po.XiuxianUserEquip;
import com.yowasa.xiuxian.exception.HandlerException;
import com.yowasa.xiuxian.service.helper.ExtendHelper;
import com.yowasa.xiuxian.service.helper.ItemHelper;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import com.yowasa.xiuxian.service.helper.UserHelper;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Set;


@CMD(name = "/装备", scope = CmdScopeEnum.ALL)
public class EqipHandler extends CmdMessageHandler {
    @Autowired
    private MessageHelper messageHelper;
    @Autowired
    private UserHelper userHelper;
    @Autowired
    private ItemHelper itemHelper;
    @Autowired
    private ItemEngine itemEngine;
    @Autowired
    private ExtendHelper extendHelper;


    @Override
    public void execute(SendMessage message) {
        UserBO user = userHelper.checkOpUser(message);
        List<String> params = getAllParam(message);

        if (StringUtils.isEmpty(params.get(0))) {
            messageHelper.replyMys(message, "可以在后面追加 装备 列表 卸下 锻造 图鉴 分解等二级指令进行后续操作");
            return;
        }
        if ("列表".equals(params.get(0))) {
            List<XiuxianUserEquip> list = itemHelper.listEqip(user.getId());
            StringBuffer sb = new StringBuffer();
            for (XiuxianUserEquip equip : list) {
                sb.append(MessageFormat.format("[{0}]{1}",QualityEnum.getById(equip.getQuality()).getName(),equip.getItemName())).append("\n");
            }
            if(sb.length() == 0){
                messageHelper.replyMys(message,"你身上还没有装备哦");
            }else {
                messageHelper.replyMys(message,sb.toString());
            }

            return;
        }
        if ("卸下".equals(params.get(0))) {
            if (params.size() < 3) {
                messageHelper.replyMys(message, "指令格式为 /装备 卸下 名称 品质，请检查格式是否正确");
                return;
            }
            String itemName = params.get(1);
            String quality = params.get(2);
            QualityEnum qualityEnum = QualityEnum.getByName(quality);
            XiuxianUserEquip myEquip = itemHelper.getMyEqipWear(user.getId(),itemName,qualityEnum.getId());
            if (myEquip == null) {
                messageHelper.replyMys(message, MessageFormat.format("身上没有穿戴名为[{0}]的装备", itemName));
                return;
            }
            String msg = itemHelper.removeEqip(user, myEquip, qualityEnum);
            ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(myEquip.getItemName());
            itemInterface.removeEffect(user);
            userHelper.rebuildBattleInfoEquip(user);
            userHelper.saveUserInfo(user);
            messageHelper.replyMys(message, msg);
            return;
        }
        if ("装备".equals(params.get(0))){
            if (params.size() < 3) {
                messageHelper.replyMys(message, "指令格式为 /装备 装备 名称 品质，请检查格式是否正确");
                return;
            }
            String itemName = params.get(1);
            String quality = params.get(2);
            QualityEnum qualityEnum = QualityEnum.getByName(quality);
            UserItemBo myItem = itemHelper.getMyEqip(user.getId(),itemName,qualityEnum.getId());
            if (myItem == null) {
                messageHelper.replyMys(message, MessageFormat.format("背包中没有名为[{0}]的装备", itemName));
                return;
            }

            String msg=itemEngine.useItem(user, myItem);
            messageHelper.replyMys(message, MessageFormat.format("你装备了[{0}],{1}", itemName, msg));
            return;
        }
        if ("锻造".equals(params.get(0))) {

            if(params.size() == 1){
                StringBuffer sb =new StringBuffer();
                sb.append("指令格式为 /装备 锻造 装备名称\n").append("你已学会的图纸有：\n");
                Set<String> knownEquipDrawing = user.getUserConfig().getKnownEquipDrawing();
                for (String drawName : knownEquipDrawing){
                    sb.append(drawName+"\n");
                }
                messageHelper.replyMys(message, sb.toString());
                return;
            }
            String name = params.get(1);
            if(!user.getUserConfig().getKnownEquipDrawing().contains(name+"图纸")){
                throw new HandlerException("你还没有学会该装备的锻造之法");
            }
            ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(name);
            if(user.getUserConfig().getGold() < itemInterface.getPrice()/10){
                throw new HandlerException("你没有足够的摩拉，本次锻造需要耗费："+itemInterface.getPrice()/10);
            }else {
                user.getUserConfig().setGold(user.getUserConfig().getGold() - itemInterface.getPrice()/10);
                userHelper.saveUserInfo(user);
            }

            //查找图纸，找出所需材料
            XiuXianDrawing draw = itemHelper.getEqipDraw(name);
            HashMap<String,Integer> hashMap = JSONUtil.toBean(draw.getSucaiDesc(), HashMap.class);
            try {
                Boolean flag = itemHelper.forgeEquipCheck(user,hashMap);
                if(flag){
                    //(UserBO user, ItemInterface itemInterface, int num,int quality)
                    //不存在的物品没有图纸，所以此处不用判空//根据仙缘，得到品质
                    int luc = user.getUserAttr().getLuc() + 20;
                    double v = luc * Math.random();
                    if(draw.getEquipName().equals("千风之诗") || draw.getEquipName().equals("千岩同心")){
                        v = 1.0;
                    }

                    Integer quality;
                    String qualityName;
                    if(v < 20){
                        quality = 1;
                        qualityName = "劣质";
                    }else if(v < 42){
                        quality = 2;
                        qualityName = "良品";
                    }else if(v < 75){
                        quality = 3;
                        qualityName = "优等";
                    }else if(v < 90){
                        quality = 4;
                        qualityName = "极品";
                    }else if(v < 100){
                        quality = 5;
                        qualityName = "绝妙";
                    }else {
                        quality = 6;
                        qualityName = "神话";
                    }
                    itemHelper.addEquip(user,itemInterface,1,quality);
                    messageHelper.replyMys(message,MessageFormat.format("锻造成功，你获得了[{0}]{1} * 1",qualityName,name));
                    return;
                }
            }catch (Exception e){
                throw e;
            }
        }
        if ("图鉴".equals(params.get(0))){
            List<XiuXianDrawing> drawingList = itemHelper.getAllDrawing(100);
            StringBuffer sb = new StringBuffer();
            sb.append("指令 /装备 图鉴 查看所有可锻造的装备\n/装备 图鉴 装备名称 查看具体所需材料\n\n");
            if (params.size() == 2){
                String name = params.get(1);
                XiuXianDrawing xiuXianDrawing = drawingList.stream().filter(i -> i.getEquipName().equals(name)).findFirst().orElse(null);
                sb.append(xiuXianDrawing.getEquipName()).append("   ").append(xiuXianDrawing.getSucaiDesc());
                messageHelper.replyMys(message,sb.toString());
            }else {
                for (XiuXianDrawing drawing : drawingList){
                    sb.append(drawing.getEquipName()).append("\n");
                }
                messageHelper.replyMys(message,sb.toString());
            }
        }
        if ("分解".equals(params.get(0))){
           if(params.size() < 3){
               throw new HandlerException("指令格式为 /装备 分解 装备名 品质");
           }

            String itemName = params.get(1);
            String quality = params.get(2);
            QualityEnum qualityEnum = QualityEnum.getByName(quality);
            UserItemBo myItem = itemHelper.getMyEqip(user.getId(),itemName,qualityEnum.getId());
            if (myItem == null) {
                messageHelper.replyMys(message, MessageFormat.format("背包中没有名为[{0}]的装备", itemName));
                return;
            }
            ItemInterface itemInterface = CommonEngine.ITEM_MAP.get(itemName);
            double v = itemInterface.getPrice() / 200 * qualityEnum.getRate();
            // 1000 5000 10000  3000 30000
            // 5    25   50     15
            // 无色 5  2 5 10 15 20
            int round = (int) Math.round(v);
            XiuXianExtend byAccountId = extendHelper.getByAccountId(user.getId());
            byAccountId.setQuintessence(byAccountId.getQuintessence() + round);
            itemHelper.dropItem(myItem, 1);
            extendHelper.updateExtendById(byAccountId);
            messageHelper.replyMys(message,"你分解了["+quality+"] "+itemName+",获得了"+round+"精粹");
        }
        return;
    }

    public String desc(){
        return new StringBuffer().append("装备相关的指令，包括装备 卸下 锻造等，/装备 列表 可查看身上穿戴的装备\n")
                .append("可通过装备图鉴查看所有存在的装备，/装备 图鉴 装备名称  可查看具体的锻造材料\n如果不存在材料，即为特殊装备，无法通过锻造获取\n部分装备存在独有的技能，装备技能不计入战技上限，但需要先配满技能再装备")
                .toString();

    }
}
